<?php
class Pageley_Serializer_Converter_File implements Pageley_Serializer_Converter {
    
    private $attribute;
    private $fileManager;

    public function __construct($attribute, $fileManager) {
        $this->attribute = $attribute;
        $this->fileManager = $fileManager;
    }
    
    public function convertIntoFormat($value) {
        return $value !== null ? $value->getLocation() : null;
    }
    
    public function convertFromFormat($value, $format = null, $serializedName = null) {
        $file = null;
        $serializedName = Pageley_Util_String::replace($serializedName, ".", "_");
        if($value !== null) {
            $file = new Pageley_Domain_BasicFile($value);
        } else if(array_key_exists($serializedName, $_FILES)) {
            $serializedName = Pageley_Util_String::replace($serializedName, ".", "_");
            $uploadInfo = $_FILES[$serializedName];
            $error = $uploadInfo["error"];
            if($error == UPLOAD_ERR_OK || $error == UPLOAD_ERR_FORM_SIZE || $error == UPLOAD_ERR_INI_SIZE) {
                $location = Pageley_Util_String::splitCamelCase($this->attribute->getName(), "-") . "/" . Pageley_Util_String::toLowerCase($uploadInfo["name"]);
                $file = new Pageley_Domain_BasicFile($location);
                $file->setUploadInfo($uploadInfo);
            } else if($error != UPLOAD_ERR_NO_FILE) {
                $message = $this->translateError($error);
                throw new Pageley_Util_IoException("Error " . $error . " during file upload: " . $message . ".");
            }
        }
        if($file !== null) {
            $file->setFileManager($this->fileManager);
        }
        return $file;
    }
    
    private function translateError($error) {
        $message = "Reason unknown";
        switch($error) {
            case UPLOAD_ERR_CANT_WRITE:
                $message = "Cannot write to temporary upload directory";
                break;
            case UPLOAD_ERR_EXTENSION:
                $message = "A PHP extension prevented file upload";
                break;
            case UPLOAD_ERR_PARTIAL:
                $message = "File was only partially uploaded";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $message = "Missing temporary upload directory";
                break;
        }
        return $message;
    }
}